package Ctr;

import DB.SalesOrderDB;
import DB.ConnectionDB;
import java.util.ArrayList;

import Model.Customer;
import Model.Product;
import Model.SalesOrder;
import Model.SalesOrderProduct;

public class SalesOrderCtr {
    private ConnectionDB connection;
    private SalesOrderDB salesOrderDB;
    private SalesOrder salesOrder;
    private ProductCtr productCtr;
    private CustomerCtr customerCtr;
    private SalesOrderProduct salesOrderProduct;
    private Customer customer;

    public SalesOrderCtr(){
        salesOrderDB = new SalesOrderDB();
        productCtr = new ProductCtr();
        customerCtr = new CustomerCtr();
        connection = ConnectionDB.getInstance();
        salesOrder = new SalesOrder();
    }

    //Creating the SalesOrder
    public void createSalesOrder(int id, String date, double totalPrice, String deliveryStatus, String deliveryDate) {
        salesOrder.setId(getMaxId());
        salesOrder.setDate(date);
        salesOrder.setTotalPrice(totalPrice);
        salesOrder.setDeliveryStatus(deliveryStatus);
        salesOrder.setDeliveryDate(deliveryDate);

        completeSalesOrder();
    }

    //Adding a product to the SalesOrder using the search
    public void addProductToSalesOrder(int id, int amount) {

        Product po = productCtr.findProduct(id);

        if (po == null) {
            throw new NullPointerException("Vare ikke fundet");
        }
        else {
            salesOrderProduct = new SalesOrderProduct(salesOrder, po, amount);
            salesOrder.addProductToSalesOrder(salesOrderProduct);
        }
    }

    //Selecting a customer
    public void selectCustomer(int id) {
        customer = customerCtr.findCustomer(id);
        salesOrder.addCustomerToSalesOrder(customer);
    }

    //Completing the SalesOrder
    public void completeSalesOrder() {
        try {
            connection.startTransaction();
            SalesOrderDB salesOrderDB = new SalesOrderDB();
            salesOrderDB.insertSalesOrder(salesOrder);
            connection.commitTransaction();
        }
        catch (Exception e) {
            connection.rollbackTransaction();
        }
    }

    public SalesOrder findSalesOrder(int id){
        return  salesOrderDB.findSalesOrder(id);
    }

    public void deleteSalesOrder(int id) {
        salesOrderDB.deleteSalesOrder(id);
    }

    public ArrayList<SalesOrder> getAllSalesOrders(){
        return salesOrderDB.getAllSalesOrders();
    }

    public ArrayList<SalesOrderProduct> getAllSalesOrderProducts() {
        return salesOrder.getSalesOrderProductList();
    }

    //GetMax
    public int getMaxId() {
        int id = salesOrderDB.salesOrderGetMax();
        return id;
    }

    //Get total price
    public double getTotalPrice() {
        return salesOrder.getTotalPrice();
    }

}
